<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="分类名称">
        <el-input
          v-model="queryParams.classifyName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          @keyup.enter.native="getClassifyTree"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="分类状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getClassifyTree"
          v-hasPermi="['product:classify:query']"
        >搜索
        </el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:classify:add']"
        >新增
        </el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['product:classify:export']"
                   @click="handleExport"
        >导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" border :data="productClassifyTreeList"
              default-expand-all
              row-key="id"
              :tree-props="{children:'children',hasChildren:'hasChildren'}"
    >
      <el-table-column prop="classifyName" label="分类名称" :show-overflow-tooltip="true"/>
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormat" align="center"/>
      <el-table-column prop="orderNum" label="排序" width="50" align="center"/>
      <el-table-column prop="remark" label="备注" min-width="200" :show-overflow-tooltip="true" v-if="false"/>
      <el-table-column prop="createBy" label="创建者" width="160" align="center" :show-overflow-tooltip="true"/>
      <el-table-column prop="createTime" label="创建时间" align="center" width="180"/>
      <el-table-column v-if="false" prop="deptName" label="组织名称" min-width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:classify:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['product:classify:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:classify:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改产品类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect v-model="form.parentId" :options="productClassifyTreeOptions" :normalizer="normalizer"
                          placeholder="选择上级分类"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="classifyName">
              <el-input v-model="form.classifyName" placeholder="请输入分类名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属组织" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptTreeOptions" :show-count="true"
                          placeholder="请选择归属组织" disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注" prop="categoryName">
              <el-input v-model="form.remark" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addClassify,
  deleteClassify,
  exportClassifyList,
  getClassifyList,
  updateClassify
} from '@/api/system/productManage'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getNodeById, getOrderNumOfList, getOrderNumOfNode } from '@/utils/ruoyi'
import { deptTreeSelect } from '@/api/system/dept'

export default {
  name: 'index',
  components: { Treeselect },
  data() {
    return {
      loading: true,
      productClassifyList: [],
      productClassifyTreeList: [],
      productClassifyTreeOptions: [],
      deptTreeOptions: [],
      queryParams: {
        classifyName: undefined,
        status: undefined
      },
      // 状态数据字典
      statusOptions: [],
      title: '',
      open: false,
      form: {
        parentId: undefined,
        classifyName: undefined,
        deptId: undefined,
        orderNum: 1,
        status: '0',
        remark: undefined
      },
      // 操作类型 add/update
      operationType: '',
      rules: {
        parentId: [
          { required: true, message: '上级分类不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '归属组织不能为空', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getClassifyTree()
    this.getDeptTreeOptions()
    this.getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    getClassifyTree() {
      this.loading = true
      getClassifyList(this.queryParams).then(response => {
        this.productClassifyList = response.rows
        this.productClassifyTreeList = this.handleTree(this.productClassifyList, 'id')
        this.getClassifyTreeOptions(this.productClassifyTreeList)
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTreeOptions() {
      deptTreeSelect().then(response => {
        this.deptTreeOptions = response.data
      })
    },
    /**
     * 给树添加顶层节点
     * @param treeList
     */
    getClassifyTreeOptions(treeList) {
      if (treeList) {
        let treeOptions = []
        // 根节点
        let rootNode = {
          id: 0,
          classifyName: '全部',
          children: []
        }
        rootNode.children = JSON.parse(JSON.stringify(treeList))

        treeOptions.push(rootNode)
        this.productClassifyTreeOptions = treeOptions
      }
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    handleUpdate(row) {
      this.reset()
      this.operationType = 'update'
      this.open = true
      this.title = '修改分类'
      let selectedClassify = getNodeById(this.productClassifyTreeList, 'id', row.id)

      if (selectedClassify) {
        this.form = { ...selectedClassify }
      }

      // treeOptions需排除自己
      let excludeTree = this.handleTree(this.productClassifyList, null, null, null, null, row.id)
      this.getClassifyTreeOptions(excludeTree)
    },
    handleAdd(row) {
      this.reset()
      this.getClassifyTreeOptions(this.productClassifyTreeList)
      this.title = '添加分类'
      this.operationType = 'add'
      this.open = true

      // 获取parentId
      let parentId = row.id
      if (!parentId) {
        parentId = 0
      }
      this.form.parentId = parentId
      this.form.deptId = 100

      // 获取orderNum
      let orderNum = 1
      // 若未选择上级节点
      if (parentId === 0) {
        orderNum = getOrderNumOfList(this.productClassifyTreeList)
      } else {
        let selectedNode = getNodeById(this.productClassifyTreeList, 'id', parentId)
        if (selectedNode) {
          orderNum = getOrderNumOfNode(selectedNode)
        }
      }
      this.form.orderNum = orderNum
    },
    handleDelete(row) {
      this.$confirm('是否删除分类"' + row.classifyName + '"?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteClassify(row.id).then(response => {
          if (response.code === 200) {
            this.msgSuccess('删除成功')
            this.getClassifyTree()
          }
        })
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.operationType === 'add') {
            addClassify(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('添加成功')
                this.open = false
                this.getClassifyTree()
              }
            })
          }
          if (this.operationType === 'update') {
            updateClassify(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getClassifyTree()
              }
            })
          }
        }
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        parentId: undefined,
        deptId: undefined,
        classifyName: undefined,
        orderNum: undefined,
        status: '0',
        remark: undefined
      }
      this.resetForm('form')
    },
    normalizer(node) {
      // 若children为空, 或不为空且长度为0, 则删除children
      if (!node.children || (node.children && !node.children.length)) {
        delete node.children
      }

      return {
        id: node.id,
        label: node.classifyName,
        children: node.children
      }
    },

    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportClassifyList(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    }
  }
}
</script>

<style scoped>

</style>
